<template>
	<view class="app-content">
		<uni_tab :tabCur.sync="tabIndex" :tab-list="tabList" @change="swiperChange"></uni_tab>
		<div class="seach_wrap">
			<div class="sort_btn_wrap">
				<div :class="{'active': sortIndex == 0}" @click="changeTabFn(0)">最新</div>
				<div :class="{'active': sortIndex == 1}" @click="changeTabFn(1)">最热</div>
			</div>
			<div class="filter_wrap">
				<div class="visit_time" @click="openPopup">
					<span>筛选</span>
					<text class="iconfont iconshaixuan" />
				</div>
			</div>
		</div>

		<screen v-if="tabActive == 0 || tabActive == 2" :filterMaskData.sync="filterMaskData" @filterQuery="filterQuery" @filterBtnCall="filterQuery" ref="screen"></screen>

		<raiders-filter v-if="tabActive == 1 || tabActive == 3" ref="raidersFilter" :filter-mask-data.sync="filterMaskData" @filterQuery="filterQuery" @filterBtnCall="filterBtnCall" />

		<div class="shop_list_wrap" v-if="tabActive == 3">
			<!-- 商城 -->
			<app-manage-list v-if="tabActive == 3" :manageData="manageData" :list="list" @onSearch="onSearch" @openPopup="openPopup" @jumpListFn="jumpListFn" :noCheck="true">
				<template v-slot:shopAwx2="{item}">
					<div class="item_list_title">
						<div>
							<span>销售价：</span>
							<span>￥ {{item.shop_price || item.cost_price }}/{{ item.goods_unit }}</span>
						</div>
						<div>
							<span>佣金：</span>
							<span class="red_text">￥{{item.profit}}/{{ item.goods_unit }}</span>
						</div>
					</div>
				</template>
				<template v-slot:shopBwx2="{item}">
					<div class="item_list_bottom">
						<div class="shop_btn_com primary_btn" @click.stop="setSaleBtnFn(1, item.goods_lib_id)">上架</div>
						<div class="shop_btn_com share_btn" @click.stop="sourceShareBtnFn(item)">
							<i class="iconfont iconfenxiang"></i>
							赚￥
							<span class="big_text">{{item.profit}}</span>
							/{{ item.goods_unit }}
						</div>
					</div>
				</template>
				<!-- 底部按钮 -->
				<template v-slot:bottomBtnWrap>
					<div class="shop_btn_wrap">
						<!-- <div class="shop_btn_com primary_btn" @click="allSetSaleBtnFn(1)">批量上架</div> -->
					</div>
				</template>
			</app-manage-list>
		</div>
		<div class="list_wrap" v-else>
			<counsel-list ref="counsel" v-if="!list.loading" :list="list" :counselData="counselData[tabActive]" @goDetail="goDetail" @popularize="popularize"></counsel-list>
		</div>

		<!-- 分享弹窗 -->
		<uni-popup ref="popupFx" maxHeight="100vh">
			<div class="share_wrap">
				<div class="share_img">
					<img :src="sharePosterImg" alt/>
				</div>
			</div>
		</uni-popup>

		<footer class="main-footer">
			<v-defooter ref="defooters" :activeIndex="0" />
		</footer>

        <input-company ref="inputCompany" @updateUserInfo="updateUserInfo"/>
	</view>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
import uniTab from '@/components/uni_tab.vue'
import Defooter from '@/pages/components/deFooter'
import CounselList from '@/pages/getGuest/components/shareCounselList.vue'
import screen from '@/components/App_screen.vue'
import RaidersFilter from '@/pages/components/RaidersFilter.vue'
import inputCompany from '@/pages/components/dialog/inputCompany'
import { getUser } from '@/utils/auth'

// api
import { getCaseWinList, getCaseSelectList, getArticleList, getArticleSelectList } from '@/api/getGuest'
import { getList, getClassList, del as posterDel } from '@/api/poster'
// 商城
import { jumpShop, verifiPhone } from '@/utils/common'
import AppManageList from '@/components/appManageList'
import uniPopup from '@/components/uni-popup/uni-popup.vue'
import manage from '@/pages/admin/manage/mixins/manage'
import { getGoodsList, getLibGoodsList, setSaleStatus, addLibGood, delGoods, goodShare } from '@/api/material'

import { list } from '@/mixins'
export default {
	name: 'winCase',
	mixins: [list, manage],
	components: {
		'v-defooter': Defooter,
		CounselList,
		uni_tab: uniTab,
		screen,
		RaidersFilter,
		AppManageList,
		uniPopup,
		inputCompany
	},
	data() {
		return {
			tabIndex: 0,
			tabActive: 0,
			tabList: [],
			sortIndex: 0,
			hostFn: [
				{
					getList: getCaseWinList,
					getSelList: getCaseSelectList,
					del: ''
				},
				{
					getList: getArticleList,
					getSelList: getArticleSelectList,
					del: ''
				},
				{
					getList: getList,
					getSelList: getClassList,
					del: posterDel
				},
				{
					getList: getLibGoodsList,
					getSelList: '',
					del: delGoods
				}
			],
			counselData: [
				{
					title: '获客案例',
					type: 'case',
					shareType: 2,
					myKey: {
						id: 'case_id',
						images: 'image_url',
						title: 'case_name'
					}
				},
				{
					title: '获客文章',
					type: 'article',
					shareType: 3,
					myKey: {
						id: 'article_id',
						images: 'cover_img',
						title: 'title',
						status: 'cat_name'
					}
				},
				{
					title: '获客海报',
					type: 'poster',
					shareType: 10,
					myKey: {
						id: 'poster_id',
						images: 'cover_image',
						title: 'copywriting'
					}
				}
			],
			form: [
				{
					name: '',
					cat_id: ''
				},
				{
					cat_id: '',
					is_public: ''
				},
				{
					poster_name: '',
					cat_id: ''
				}
			],
			filterMaskData: [],
			filterMaskDataAll: [
				[
					{
						title: '装修风格',
						// type: 2,
						key: 'case_style',
						list: []
					},
					{
						title: '标签',
						// type: 2,
						key: 'is_public',
						list: []
					},
					{
						title: '来源',
						// type: 2,
						key: 'source_type',
						list: []
					}
				],
				[
					{
						title: '一级分类',
						list: []
					},
					{
						title: '二级分类',
						list: []
					},
					{
						title: '标签',
						list: [],
						hide: false
					},
					{
						title: '来源',
						list: [],
						hide: false
					}
				],
				[
					{
						title: '线上海报',
						// type: 2,
						key: 'cat_id',
						list: []
					},
					{
						title: '来源',
						key: 'source_type',
						list: [
							{
								name: '平台',
								id: 1,
								status: false
							},
							{
								name: '我的',
								id: 2,
								status: false
							}
						]
					}
				],
				// 商品
				[
					{
						title: '排序（降序）',
						// type: 2,
						key: 'source_type',
						list: [
							{
								name: '销量',
								status: false,
								id: 1,
								key: 'source_type'
							},
							{
								name: '佣金',
								status: false,
								id: 2,
								key: 'source_type'
							}
						]
					},
					{
						title: '类型',
						key: 'cat_id',
						list: []
					},
					{
						title: '二级分类',
						type: 2,
						key: 'cat_id',
						list: [],
						hide: false
					}
				]
			]
		}
	},
	computed: {
		...mapGetters({ userInfo: 'getUser' })
	},
	onLoad(option) {
		this.option = option
		getUser().then(res => {
			const { role_id, nick_name } = this.userInfo
			if ((role_id == 1 || role_id == 2) && (!nick_name || verifiPhone(nick_name))) {
				this.$refs.inputCompany.openPopup()
			}
			this.init()
		})
	},
	// 下拉刷新
	onPullDownRefresh() {
		let that = this
		this.resetList()
		this.getList(this.option).then(res => {
			uni.stopPullDownRefresh()
		})
	},
	// 加载更多
	onReachBottom() {
		if (this.list.loading) {
			return
		}
		if (this.list.data.length < this.list.total) {
			this.getList(this.option).then(res => {
				uni.stopPullDownRefresh()
			})
		} else {
			uni.stopPullDownRefresh()
			uni.showToast({
				title: '没有更多了',
				duration: 2000,
				icon: 'none'
			})
		}
	},
	methods: {
		// ===初始化===
		init() {
			if (this.userInfo.role_id == 2) {
				this.tabList = [{ name: '严选爆款', key: 3 }, { name: '精品案例', key: 0 }, { name: '装修攻略', key: 1 }, { name: '推广海报', key: 2 }]
			} else {
				this.tabList = [{ name: '精品案例', key: 0 }, { name: '装修攻略', key: 1 }, { name: '推广海报', key: 2 }]
			}
			this.tabActive = this.tabList[0].key

			if (this.option.tabIndex) {
				this.tabIndex = this.option.tabIndex
				this.tabActive = this.tabList[this.tabIndex].key
			}

			console.log(this.tabActive)

			this.filterMaskData = JSON.parse(JSON.stringify(this.filterMaskDataAll[this.tabActive]))
			this.getList()
			if (this.tabActive != 3) {
				this.getSelectList()
			}
		},
		updateUserInfo() {
			uni.showLoading({
				title: '修改成功...'
			})
			// getBasicUser(this.owner_user_id, true);
			getUser(true).then((res) => {
				this.$refs.inputCompany.closePopup()
				uni.hideLoading()
			})
		},
		// ===切换tab===
		swiperChange(index) {
			this.tabIndex = index
			this.tabActive = this.tabList[index].key
			this.filterMaskData = JSON.parse(JSON.stringify(this.filterMaskDataAll[this.tabActive]))
			this.form = [
				{
					name: '',
					cat_id: ''
				},
				{
					cat_id: '',
					is_public: ''
				},
				{
					poster_name: '',
					cat_id: ''
				}
			]

			this.filterQuery()
			if (this.tabActive != 3) {
				this.getSelectList()
			}
		},
		openPopup() {
			if (this.tabActive == 1 || this.tabActive == 3) {
				this.$refs.raidersFilter.$refs.screen.openPopup()
			} else {
				this.$refs.screen.openPopup()
			}
		},
		// ===切换最热===
		changeTabFn(index) {
			this.sortIndex = index
			this.resetList()
			this.getList()
		},
		// ===筛选===
		getSelectList() {
			let that = this
			this.hostFn[this.tabActive].getSelList().then(res => {
				if (res.status === 'success') {
					if (this.tabActive == 0) {
						that.filterMaskData[0].list = that.formatSelect(res.data.style_list)
						that.filterMaskData[1].list = that.formatSelect(res.data.type_list)
						that.filterMaskData[2].list = that.formatSelect(res.data.source_type_list)
					} else if (this.tabActive == 1) {
						that.filterMaskData[0].list = that.$refs.raidersFilter.formatSelect(res.data.class_list)
						that.filterMaskData[2].list = that.$refs.raidersFilter.formatTypeSelect(res.data.type_list)
						that.filterMaskData[3].list = that.$refs.raidersFilter.formatTypeSelect(res.data.source_type_list)
					} else if (this.tabActive == 2) {
						that.filterMaskData[0].list = res.data[0].cat_list.map(i => ({
							name: i.cat_name,
							id: i.cat_id,
							status: false
						}))
					}
				}
			})
		},
		// ===列表数据===
		getList() {
			let that = this

			let params = {
				page: that.list.page,
				limit: that.list.limit
			}
			if (this.tabActive == 3) {
				let hostData = this.manageData

				// 是否有搜索
				if (hostData.search) {
					params.keyword = hostData.search
				}
				// 是否有筛选分类
				if (!this.$util.isEmpty(hostData.isFilterList.catData)) {
				// params.category_id = hostData.isFilterList.catData.id
					params.category_id = hostData.isFilterList.catData.map(arr => arr.id)
				}
				// 是否有筛选排序
				if (hostData.isFilterList.source_type) {
					// if (this.tabActive == 2) {
					params.order_by_sale = hostData.source_type
					// } else {
					// 	params.order_by = hostData.source_type
					// }
				}
			} else {
				params = {
					...params,
					owner_user_id: that.option.owner_user_id,
					...that.form[that.tabActive]
				}
			}

			console.log('params', params)
			params.order = this.sortIndex == 1 ? 'hottest' : 'newest'
			return this.hostFn[this.tabActive].getList(params).then(res => {
				if (this.tabActive == 3) {
					let data = res.data
					for (let i in data.list) {
						let item = data.list[i]
						item.status = false
						item._optionId = item.goods_lib_id
						item._imgUrl = item.goods_image
						item._title = item.goods_name
						item._isSelf = item.is_self || 0
						item._isSelfText = item.is_self == 1 ? '自营' : '代销'

						// 金额保留两位
						let arr = ['cost_price', 'profit']
						for (let j = 0; j < arr.length; j++) {
						    let nowData = arr[j]
							item[nowData] = this.toFix(item[nowData])
						}
					}

					that.completes(res)

					this.formatShopClass(res.data.category_list)
				} else {
					that.completes(res)
				}
			})
		},
		// 商城方法
		// 上下架
		setSaleBtnFn(type, id) {
			let params = {
				status: type
			}
			// if (this.tabActive == 2) {
			params.goods_lib_id = id
			// } else {
			// 	params.goods_id = id
			// }

			this.setSaleStatusFn(addLibGood, params, type, () => {
				this.resize()
			})
		},
		// == 货源商品分享==
		sourceShareBtnFn(item) {
		    let that = this
			uni.showModal({
				title: '提示',
				content: '分享后将自动将该商品上架至您的店铺',
				success: function(res) {
					if (res.confirm) {
						let params = {
							goods_lib_id: item.goods_lib_id,
							status: 1
						}
						// 上架
						addLibGood(params).then(res => {
							if (res.status === 'success') {
								let paramsChild = {
									goods_id: res.data.goods_id_arr[0],
									price: item.cost_price,
									share_type: 0
								}
								that.goodShareFn(paramsChild)
								that.resize()
							}
						})
					} else if (res.cancel) {
						console.log('用户点击取消')
					}
				}
			})
		},
		// ==列表分享按钮==
		goodShareFn(hostData) {
			goodShare(hostData).then(res => {
				if (res.status === 'success') {
					this.sharePosterImg = res.data
					let arr = []
					arr[0] = this.sharePosterImg
					uni.previewImage({
						current: this.sharePosterImg,
						urls: arr
					})
					// this.$refs.popupFx.open()
				}
			})
		},
		resize() {
			let data = this.manageData
			data.checkList = []
			this.resetList()
			this.getList()
		},
		toFix(val) { return Number(val).toFixed(2) },
		// 格式化商城分类筛选
		formatShopClass(filterData) {
			// let filterMaskData = this.tabActive == 2 ? this.allFilterMaskData[1] : this.filterMaskData[1]
			// filterMaskData.list = this.$refs.raidersFilter.formatSelect(filterData, filterMaskData.key, filterMaskData.noMulti || false)

			// this.filterMaskData = this.commonJS.deepCopy(this.allFilterMaskData)

			let filterMaskData = this.filterMaskData[1]

			filterMaskData.list = this.$refs.raidersFilter.formatSelect(filterData, filterMaskData.key, filterMaskData.noMulti || false)

			console.log(this.filterMaskData)
		},
		// 筛选格式化
		formatSelect(data) {
			return data.map(i => ({
				name: i.style_name ? i.style_name : i.type_name ? i.type_name : i.type_name,
				status: false,
				id: i.style_id ? i.style_id : i.is_public ? i.is_public : i.source_type,
				type: i.is_public ? 'type_list' : i.source_type ? 'source_type' : ''
			}))
		},
		// ===递归筛选===
		filterBtnCall(items) {
			if (this.tabActive == 3) {
				let data = this.manageData

				console.log(items)
				// 多选
				if (items.value == 'multi') {
					this.filterMaskData[2].list = items.list
				}

				if (items.key == 'source_type') {
					data.isFilterList.sourceData = ''
					data.isFilterList.sourceData = items.status ? items : ''
				} else {
					if (items.value == 'multi') {
						data.isFilterList.catData = []
					}

					if (items.status) {
						data.isFilterList.catData.push(items)
					} else {
						data.isFilterList.catData = data.isFilterList.catData.filter(filterItem => filterItem.id != items.id)
					}
				}
				this.resize()
			} else {
				if (items.value === 'multi') {
					this.filterMaskData[1].list = items.list
				}
				if (items.value === 'type_list') {
					this.form[this.tabActive].is_public = items.status ? items.id : ''
				} else if (items.value === 'source_type') {
					this.form[this.tabActive].source_type = items.status ? items.id : ''
				} else {
					this.form[this.tabActive].cat_id = items.status ? items.id : ''
				}
				this.resetList()
				this.getList()
			}
		},
		// ===重置筛选===
		filterQuery(val) {
			if (this.tabActive == 1) {
				this.filterMaskData[1].list = []
				// this.getSelectList()
				this.form[this.tabActive] = {
					cat_id: '',
					is_public: '',
					source_type: ''
				}
			} if (this.tabActive == 3) {
				this.manageData.isFilterList.catData = []
				this.manageData.isFilterList.sourceData = ''

				// this.filterMaskData = this.commonJS.deepCopy(this.allFilterMaskData)
				this.resize()
			} else {
				let form = val ? val.form : {}
				this.form[this.tabActive] = {
					...this.form[this.tabActive],
					...form
				}
			}
			this.resetList()
			this.getList()
		},
		// 推广获客
		popularize(val) {
			this.$nextTick(() => {
				this.$refs.counsel.$refs.sharePoster.showMask(
					{
						id: val[this.counselData[this.tabActive].myKey.id],
						url: true
					},
					true
				)
			})
		},
		// 进入详情
		goDetail(val) {
			if (this.tabActive == 0) {
				let query = {
					mainId: val.case_id,
					caseid: 'null',
					owner_user_id: this.option.owner_user_id
				}
				uni.navigateTo({
					url: `/pages/case/casedetail${this.commonJS.queryData(query)}`
				})
			} else if (this.tabActive == 1) {
				let query = {
					mainId: val.article_id,
					articleid: 'null',
					owner_user_id: this.option.owner_user_id
				}
				uni.navigateTo({
					url: `/pages/getGuest/articledetail${this.commonJS.queryData(query)}`
				})
			} else {
				let query = {
					poster_id: val.poster_id,
					owner_user_id: this.option.owner_user_id
				}
				uni.navigateTo({
					url: `/pages/getGuest/poster/onlineDetail${this.commonJS.queryData(query)}`
				})
			}
		},
		// 商品功能 ============
		// ==跳转商城==
		jumpListFn(item) {
			let goods_id = item.lib_goods_id
			if (!goods_id) {
				this.$toast('暂无该货源商品详情！')
				return false
			}
			let jumpUrl = '/goods/' + goods_id
			jumpShop(jumpUrl, this.userInfo.user_picture)
		}
	}
}
</script>

<style lang="scss" scoped>
	.list_wrap {
		margin-top: 180px;
		border-top: 1px solid #f5f5f5;
	}
	.seach_wrap {
		position: fixed;
		top: 92px;
		width: 100%;
		font-size: 28px;
		background-color: #fff;
		@include direction(center, space-between);
		z-index: 99;
		box-shadow: 0px 4px 6px 0px rgba(221, 221, 221, 0.3);
		.sort_btn_wrap {
			@include disFlexCen();
			& > div {
				color: #666666;
				margin: 30px;
			}
			.active {
				color: $auxiliaryColor2;
			}
		}
		.filter_wrap {
			padding: 0 30px;
			display: flex;
			justify-content: center;
			align-items: center;
			position: relative;
			color: #666666;
			border-right: 1px;
			& > div {
				padding: 0 5px;
			}
			&::after {
				content: '';
				height: 60px;
				position: absolute;
				background-color: #dddddd;
				width: 1px;
				left: 0;
				top: 50%;
				transform: translate(0, -50%);
			}
		}
	}
	// 商城样式
	.shop_list_wrap {
		// =================================
		.share_wrap{
			.share_img{
				width: 100%;
				height: 85vh;
			}
		}

		// 公共商品分享弹窗
		.shareGoodsMask {
			width: 70%;
			border-radius: 5px; /*no*/
		}

		.share_info {
			margin-top: 10px;

			& > div {
				margin-top: 10px;
			}

			#moduleUserAttr {
				margin-right: 10px;
			}
		}

		// 公共按钮
		.shop_btn_com {
			display: flex;
			align-items: center;
			height: 56px;
			padding: 0 40px;
			font-size: 30px;
			border-radius: 50px;
			border: 1px solid $borderColorMain; /*no*/
			margin-left: 20px;
		}

		.primary_btn {
			color: #3a1b04;
			background-color: $mainColor;
			border: 1px solid $mainColor;
		}

		.no_primary_btn {
			color: #fff;
			background-color: #ccc;
			border: 1px solid #ccc;
		}

		.red_text {
			color: #e43c36;
		}

		.sub_text_color {
			color: $fontColor2;
		}

		img {
			display: block;
			width: 100%;
			height: 100%;
		}

		.pop_tip {
			padding: 30px 0 0;
			width: 560px;
			overflow: hidden;
			background-color: #fff;

			h3 {
				padding: 0 40px 20px;
				line-height: 60px;
				font-size: 32px;
			}

			.txt {
				padding: 0 40px 20px;
				line-height: 44px;
				font-size: 28px;
				color: #666;
			}

			.btn {
				display: flex;
				border-top: 1px solid #ddd;

				uni-button {
					font-size: 28px;
					flex: 1;
					background: none;
					border: none;
					line-height: 90px;
					border-radius: 0;
					&:after{
						border-radius: 0;
						border: none;
					}
				}

				button + button {
					border-left: 1px solid #ddd;
				}

				.buttonBox1{
					width: 100%;
					height: 80px;
					line-height: 80px;
					font-size: 30px;
				}
				.buttonBox2{
					width: 50%;
					height: 80px;
					line-height: 80px;
					font-size: 30px;
					&+.buttonBox2{
						border-left: 2px solid #ddd;
					}
				}
				.yes {
					color: #ff6900;
				}
			}
		}
		// ==================================
		.item_list_title {
			display: flex;
			flex-direction: column;
			justify-content: space-around;
			flex: 1;
			min-height: 90px;
		}
		.item_list_bottom {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			margin-top: 30px;

			.share_btn {
				color: #fff;
				border-color: #ff7d6d;
				background: linear-gradient(90deg, #ff7d6d, #ff4444);
				font-size: 24px;
				padding: 0 30px;
				.iconfenxiang {
					font-size: 24px;
				}

				i {
					margin-right: 8px;
				}

				.big_text {
					font-size: 32px;
				}
			}
		}
		.shop_btn_wrap {
			display: flex;
			align-items: center;
		}
	}
</style>
<style lang="scss">
.shop_list_wrap {

}
</style>
